const { io } = require("./app");
const { createGroup, joinGroup, sendMessage } = require("./db/database");


io.on("connection", (socket) => {
  console.log("用户已连接");

  socket.on("createGroup", (group) => {
    createGroup(group);
    console.log(`群组创建: ${group}`);
  });

  socket.on("joinGroup", (data) => {
    joinGroup(data.group, data.user);
    socket.join(data.group);
    console.log(`用户 ${data.user} 加入群组: ${data.group}`);
  });

  socket.on("message", (msg) => {
    sendMessage(msg);
    console.log(`消息发送至群组: ${msg.group}`);
    io.to(msg.group).emit("message", msg);
  });

  socket.on("disconnect", () => {
    console.log("用户已断开连接");
  });
});
